#!/usr/bin/env bash
#
# Copyright (C) 2017,2021 Leah Rowe <info@minifree.org>
# Copyright (C) 2017 Alyssa Rosenzweig <alyssa@rosenzweig.io>
# Copyright (C) 2017 Michael Reed <michael@michaelreed.io>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

[ "x${DEBUG+set}" = 'xset' ] && set -v
set -e

# Always update it no matter what.
# download-www doesn't reset git revisions
# Only build/release/src resets the revision
./download www

if [ ! -d osbwww ]; then
	printf "ERROR: osbmk-www: Could not download osbwww\n"
	exit 1
fi

# If any html files exist for md files that no longer exist:
for htmlfile in $(find -L osbwww/www/ -name '*.html'); do
	if [ ! -f "${htmlfile%.html}.md" ]; then
		rm -f "${htmlfile}"
	fi
done

# usage: title file
title() {
    sed -n 1p "osbwww/www/news/${1}" | sed -e s-^..--
}

# usage: meta file
meta() {
    file="${1}"
    URL=$(printf '%s\n' "${file%.md}.html")

    printf '%s\n' "[$(title "$file")]($URL){.title}"
    printf '%s\n' "[$(sed -n 3p "osbwww/www/news/${file}" | sed -e s-^..--)]{.date}"
    printf '\n'
    tail -n +5 "osbwww/www/news/${file}" | perl -p0e 's/(\.|\?|\!)( |\n)(.|\n)*/.../g'

    printf '\n'
    printf '\n'
}

# usage: rss_header
rss_header() {
    printf '%s\n' '<rss version="2.0">'
    printf '%s\n' '<channel>'

    printf '%s\n' "<title>$BLOGTITLE</title>"
    printf '%s\n' "<link>${BLOGBASE}news/</link>"
    printf '%s\n' "<description>$BLOGDESCRIPTION</description>"
}

# usage: rss_main file
rss_main() {
    file="${1}"

    # render content and escape
    htmlfile="${file%.md}.html"

    printf '%s\n' '<item>'
    printf '%s\n' "<title>$(title "${file}")</title>"
    printf '%s\n' "<link>${BLOGBASE}news/${htmlfile}</link>"
    printf '%s\n' '</item>'
}

# usage: rss_footer
rss_footer() {
    printf '%s\n' '</channel>'
    printf '%s\n' '</rss>'
}


mkhtml() {
	FILE=${1%.md}

	if [ ! -f "${FILE}.md" ]; then
		printf "mkhtml(): '%s' does not exist" "${FILE}.md"
		return 1
	fi

	rm -f "${FILE}.html"

	printf "Generating '%s' from '%s'\n" "${FILE}.html" "${FILE}.md"

	TMPFILE=$(mktemp -t osboot_www.XXXXXXXXXX)

	cat "$1" > "$TMPFILE"

	OPTS="-T osboot"

	if [[ $FILE == "osbwww/www/index" || $FILE == "./osbwww/www/index" ]]; then
		TEMPLATE="resources/www/template.homepage.html"
		OPTS="--css /headercenter.css"
	else
		TEMPLATE="resources/www/template.html"
	fi

	if [[ ${FILE%/*} == "osbwww/www/news" ]] && [[ $FILE != "osbwww/www/news/index" ]]
	then
		TEMPLATE="resources/www/template.newsarticle.html"
	fi
	if [[ ${FILE%/*} == "./osbwww/www/news" ]] && [[ $FILE != "./osbwww/www/news/index" ]]
	then
		TEMPLATE="resources/www/template.newsarticle.html"
	fi

	if [[ $FILE != "osbwww/www/docs/fdl-1.3" && \
			$FILE != "osbwww/www/docs/install/rpi_setup" && \
			$FILE != "osbwww/www/conduct" ]]; then
		cat resources/www/footer.md >> "$TMPFILE"
	fi

	# change out .md -> .html
	sed -i -e 's/\.md\(#[a-zA-Z0-9_-]*\)\?\([])]*\)/.html\1\2/g' "$TMPFILE"

	# work around issue #2872
	TOC=$(grep -q "^x-toc-enable: true$" "$TMPFILE" && printf '%s\n' "--toc --toc-depth=2") || TOC=""

	# work around heterogenous pandoc versions
	SMART=$(pandoc -v | grep -q '2\.0' || printf '%s\n' "-f markdown+smart -t html") || SMART=""

	# chuck through pandoc
	#
	# $OPTS must not be quoted, otherwise pandoc interprets '--css /headercenter.css'
	# as one argument, when it is actually two.
	pandoc $TOC $SMART "$TMPFILE" -s --css /global.css $OPTS \
		--template "${TEMPLATE}" --metadata return="" > "$FILE.html"

	# generate section title anchors as [link]
	sed -i -e 's_^<h\([123]\) id="\(.*\)">\(.*\)</h\1>_<div class="h"><h\1 id="\2">\3</h\1><a aria-hidden="true" href="#\2">[link]</a></div>_' "$FILE.html"

	# clean up temporary file
	rm -f "$TMPFILE"
	return 0
}

BLOGTITLE="osboot News"
BLOGBASE="https://osboot.org/"
BLOGDESCRIPTION="News on osboot development"

# Dermine the order of news articles in news/index.md and news/feed.xml
FILES="$(cat resources/www/news-order)"
for f in ${FILES}; do
	if [ ! -f "osbwww/www/news/${f}" ]; then
		printf "build/html/news: news file '%s' does not exist" "${f}"
		exit 1
	fi
done

# generate the index file
cat resources/www/news-header.md > osbwww/www/news/index.md
for f in $FILES
do
    meta "${f}" >> osbwww/www/news/index.md
done

# generate the RSS index
rss_header > osbwww/www/news/feed.xml
for f in $FILES
do
    rss_main "$f" >> osbwww/www/news/feed.xml
done
rss_footer >> osbwww/www/news/feed.xml

cp osbwww/www/news/feed.xml osbwww/www/feed.xml

if [ $# -gt 0 ]; then
	for mdfile in ${@}; do
		mkhtml "${mdfile}"
	done
else
	for mdfile in $(find -L osbwww/www/ -name '*.md'); do
		mkhtml "${mdfile}"
	done
fi

